import * as os from "os"
import common from '../../../dxmodules/dxCommon.js'
import logger from "../../../dxmodules/dxLogger.js"
const utils = {}

// Get the download size (in bytes) of the URL file.
utils.getUrlFileSize = function (url) {
    let actualSize = common.systemWithRes(`wget --spider -S ${url} 2>&1 | grep 'Length' | awk '{print $2}'`, 100).match(/\d+/g)
    return actualSize ? parseInt(actualSize) : 0
}
// Check if it is ""/null/undefined
utils.isEmpty = function (str) {
    return (str === "" || str === null || str === undefined)
}
/**
 * Convert the parsed string to JSON, and note that the value should not contain a single quote (").
 * @param {string} inputString 
 * @returns 
 */
utils.parseString = function (inputString) {
    // Get the contents between {}
    inputString = inputString.slice(inputString.indexOf("{"), inputString.lastIndexOf("}") + 1)
    // The regular expression `key=value` specifies the key, which is `\w+` (alphanumeric underscores, case sensitive), and spaces are allowed on both sides of the `=` symbol. The value is either `\w+` or the content between two consecutive `"` characters (including `"`).
    const keyValueRegex = /(\w+)\s*=\s*("[^"]*"|\w+(\.\w+)?)/g;
    let jsonObject = {};
    let match;
    while ((match = keyValueRegex.exec(inputString)) !== null) {
        let key = match[1];
        let value = match[2]
        if (/^\d+$/.test(value)) {
            value = parseInt(value)
        } else if (/^\d+\.\d+$/.test(value)) {
            value = parseFloat(value)
        } else if (value == 'true') {
            value = true
        } else if (value == 'false') {
            value = false
        } else {
            value = value.replace(/"/g, '').trim()
        }
        jsonObject[key] = value;
    }
    return jsonObject;
}

/**
 * Wait for the download result. Note that the timeout period must not exceed the dog-feeding time, otherwise the download will restart if it is slow.
 * @param {string} update_addr Download link
 * @param {string} downloadPath Storage path
 * @param {number} timeout time out
 * @param {string} update_md5 MD5 checksum
 * @param {number} fileSize File size
 * @returns Download results (bool)
 */
utils.waitDownload = function (update_addr, downloadPath, timeout, update_md5, fileSize) {
    // Delete the original file
    common.systemBrief(`rm -rf "${downloadPath}"`)
    // Asynchronous download
    common.systemBrief(`wget -c "${update_addr}" -O "${downloadPath}" &`)
    let startTime = new Date().getTime()
    while (true) {
        // Calculate the size of the downloaded files
        let size = parseInt(common.systemWithRes(`file="${downloadPath}"; [ -e "$file" ] && wc -c "$file" | awk '{print $1}' || echo "0"`, 100).split(/\s/g)[0])
        // If they are equal, the download was successful.
        if (size == fileSize) {
            let ret = common.md5HashFile(downloadPath)
            if (ret) {
                let md5 = ret.map(v => v.toString(16).padStart(2, '0')).join('')
                if (md5 == update_md5) {
                    // MD5 checksum success returns true.
                    return true
                }
            }
            common.systemBrief(`rm -rf "${downloadPath}"`)
            // MD5 checksum failure returns false.
            return false
        }
        // If the download times out, delete the downloaded file and restart the computer to stop asynchronous downloads.
        if (new Date().getTime() - startTime > timeout) {
            vf203.pwm.fail()
            common.systemBrief(`rm -rf "${downloadPath}"`)
            // Restart immediately
            this.restart()
            return false
        }
        os.sleep(100)
    }
}
// Restart immediately
utils.restart = function () {
    common.systemBrief("reboot -f")
}

export default utils
